package com.vict.service;

import com.vict.bean.DbConfig;
import com.vict.config.SettingConfig;
import com.vict.exce.MessageEx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DbService {

    public static DbService dbService;

    @Autowired
    public void setDbService(DbService dbService){
        DbService.dbService = dbService;
    }

    public void addDbConfig(String name, String url, String username, String password){
        if(name == null || name.trim().equals("")){
            throw new MessageEx("name不可为空");
        }
        if(url == null || url.trim().equals("")){
            throw new MessageEx("url不可为空");
        }
        if(username == null || username.trim().equals("")){
            throw new MessageEx("username不可为空");
        }
        if(password == null || password.trim().equals("")){
            throw new MessageEx("password不可为空");
        }

        DbConfig dbConfig = new DbConfig();
        dbConfig.setName(name);
        dbConfig.setUrl(url);
        dbConfig.setUsername(username);
        dbConfig.setPassword(password);

        List<DbConfig> dbConfigList = SettingConfig.getDbConfigList();
        if(dbConfigList == null){
            dbConfigList = new ArrayList<>();
        }
        dbConfigList.add(dbConfig);
        SettingConfig.saveDbConfig(dbConfigList);
    }

    public void updateDbConfig(int index, String name, String url, String username, String password) {
        if(name == null || name.trim().equals("")){
            throw new MessageEx("name不可为空");
        }
        if(url == null || url.trim().equals("")){
            throw new MessageEx("url不可为空");
        }
        if(username == null || username.trim().equals("")){
            throw new MessageEx("username不可为空");
        }
        if(password == null || password.trim().equals("")){
            throw new MessageEx("password不可为空");
        }

        List<DbConfig> dbConfigList = SettingConfig.getDbConfigList();
        DbConfig dbConfig = dbConfigList.get(index);
        dbConfig.setName(name);
        dbConfig.setUrl(url);
        dbConfig.setUsername(username);
        dbConfig.setPassword(password);
        SettingConfig.saveDbConfig(dbConfigList);
    }
}
